package com.wframe.project.jnd.wx.controller;

import com.frame.common.ValidateNumber;
import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.frame.metadata.wordbook.WordbookService;
import com.frame.util.EncryptUtil;
import com.frame.util.SelectItem;
import com.wframe.project.jnd.extinterface.sms.SmsUtil;
import com.wframe.project.jnd.rest.util.*;
import com.wframe.project.jnd.services.*;
import com.wframe.project.jnd.util.ServletUtils;
import com.wframe.project.jnd.util.WebUtils;
import com.wframe.project.jnd.wx.filter.WechatFilter;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.session.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 用户信息相关控制器
 * Created by Administrator on 2017/4/13.
 */
@Controller
@RequestMapping("we/user")
public class WeUserController {

    @Autowired
    UserService userService;
    @Autowired
    AddressService addressService;
    CouponService couponService;
    @Autowired
    InformationService informationService;
    @Autowired
    OrderService orderService;


    @RequestMapping("/login")
    public String loginPage(HttpSession session, Model model) {
        WxMpUser wxMpUser = (WxMpUser) session.getAttribute(WechatFilter.WECHAT_USER_KEY);
        model.addAttribute("showBindWechat", wxMpUser != null);
        return "/wesite/view/sign/login";
    }

    @RequestMapping("/loginUser")
    public void login(String loginname, String pwd, String checkcode, Boolean bindwechat, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            JdataBean loginUser = userService.login(loginname, pwd, checkcode, bindwechat, session);
            if (loginUser != null) {
                SessionUser sessionuser = new SessionUser();

                sessionuser.setUserid(loginUser.getString("id"));
                sessionuser.setUsername(loginUser.getString("username"));
                String title = loginUser.getString("nickname");
                if (StringUtils.isBlank(title)) {
                    title = loginUser.getString("loginname");
                }
                sessionuser.setTitle(title);
                sessionuser.setComname(loginUser.getString("comname"));
                if (loginUser.getInt("authstate") == 2) {
                    sessionuser.setAuth(true);
                }

                WebSession.setWbUser(session, sessionuser);
            }

            json.putData(loginUser);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    //会员中心
    @RequestMapping(value = "/wehome")
    public String home(HttpServletRequest request, Model model) throws ClientException {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            model.addAttribute("requesturl", request.getRequestURI());
            return "/wesite/view/sign/login";
        }
        JdataBean user = userService.getUser(WebSession.getWbUser(request.getSession()).getUserid());
        if (StringUtils.isNotBlank(user.getString("grade"))) {
            try {
                SelectItem item = WordbookService.getIntance().getItemName("UserGrade", user.getString("grade"));
                if (item != null) {
                    user.put("gradename", item.getText());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        JdataBean address = addressService.getCompanyAddress(WebSession.getWbUser(request.getSession()).getUserid());
        if (address != null)

            model.addAttribute("address", address.getDataMap());
        model.addAttribute("user", user.getDataMap());
        return "/wesite/view/home/userinfo";
    }

    /**
     * 用户注销
     *
     * @param session
     * @param response
     */
    @RequestMapping(value = "/weloginout")
    public void loginoutwe(String openid, String userid, HttpSession session, HttpServletResponse response, HttpServletRequest request) throws Exception {
        if (StringUtils.isBlank(userid)) {
            userid = WebSession.getWbUser(request.getSession()).getUserid();
        }
        WebSession.removeWbUser(session);
        if (StringUtils.isNotBlank(userid) && ServletUtils.inWechat(request)) {
            userService.wxLoginOutwe(null, userid);
        }
        JsonReturn json = new JsonReturn();
        try {
            WebUtils.responseWrite(response, json.toString());

        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 修改用户基本信息
     */
    @RequestMapping(value = "/weeditsave")
    public void weeditsave(HttpServletRequest request, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            WebSession.checkLogin(request.getSession());
            JdataBean parms = WebUtils.requestMapToBean(request.getParameterMap());
            String type = parms.getString("type");
            parms.remove("type");
            parms.put("id", WebSession.getWbUser(request.getSession()).getUserid());
            if ("nick".equals(type)) parms.put("title", parms.getString("nickname"));
            userService.editUser(parms);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 发送短信验证码
     *
     * @param response
     */
    @RequestMapping(value = "/sendsms")
    public void sendsms(String mobile, String smstype, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            if ("reg".equals(smstype)) {
                new SmsUtil().sendRegCode(mobile);
            } else if ("changephone".equals(smstype)) {
                new SmsUtil().sendChangephoneCode(mobile);
            } else if ("findpwd".equals(smstype)) {
                new SmsUtil().sendFindCode(mobile);
            }
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 验证短信验证码
     *
     * @param response
     */
    @RequestMapping(value = "/checksmscode")
    public void checksmscode(String mobile, String smscode, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            json.putData(String.valueOf(new SmsUtil().smsCheck(mobile, smscode)));
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 检查账号
     *
     * @param loginname
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/checkloginphone")
    public void checkLoginPhone(String loginname, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            json.putData(userService.checkloginname(loginname));
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 检查图形验证码
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/checkimgcode")
    public void checkimgcode(String code, HttpSession session, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            json.putData(ValidateNumber.checkAll(code, session));
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 找回设置新密码
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/findpwd")
    public void findpwd(String userid, String phone, String smscode, String newpwd, HttpServletResponse response) throws Exception {
        JsonReturn json = new JsonReturn();
        try {
            userService.findpwd(userid, phone, smscode, newpwd);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    @RequestMapping(value = "/nickname1")
    public String UpNickName(HttpServletRequest request, Model model) throws ClientException {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            return "/wesite/view/sign/login";
        }
        JdataBean user = userService.getUser(WebSession.getWbUser(request.getSession()).getUserid());
        model.addAttribute("user", user.getDataMap());
        return "/wesite/view/home/upnickname";
    }

    /**
     * 进入修改密码页面
     * by ljh
     *
     * @param request
     * @param model
     * @return
     * @throws ClientException
     */
    @RequestMapping(value = "/settpassword")
    public String SetPassWord(HttpServletRequest request, Model model) throws ClientException {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            return "/wesite/view/sign/login";
        }
        JdataBean user = userService.getUser(WebSession.getWbUser(request.getSession()).getUserid());
        model.addAttribute("phone", user.getString("phone"));
        model.addAttribute("loginpwd",user.getString("loginpwd"));
        return "/wesite/view/home/reset-password";
    }

    /**
     * 修改密码
     */
    @RequestMapping(value = "/wechangepwd")
    public void changepwd(String oldpwd, String newpwd, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            JdataBean user = userService.getUser(WebSession.getWbUser(session).getUserid());
            String oldpwd_md5 = EncryptUtil.md5Encode(oldpwd);
            if(!user.getString("loginpwd").equalsIgnoreCase(oldpwd_md5)){
                throw new ClientException(CodeEnum.Errpwd);
            }
            userService.updatePwd(oldpwd, newpwd, session);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 验证原始手机号码
     */
    @RequestMapping(value = "/showchangephone")
    public String showchangephone(HttpServletRequest request, Model model) {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            model.addAttribute("requesturl", request.getRequestURI());
            return "/wesite/view/sign/login";
        }
        JdataBean user = userService.getUser(WebSession.getWbUser(request.getSession()).getUserid());
        model.addAttribute("user", user.getDataMap());
        return "/wesite/view/home/wxchangePhone";
    }

    /**
     * 更换手机绑定
     *
     * @param response
     */
    @RequestMapping(value = "/wechangephone")
    public void changephone(String oldphone, String newphone, String oldsmscode, String newsmscode, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            userService.changephone(oldphone, newphone, oldsmscode, newsmscode, session);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 显示手机绑定页面
     */
    @RequestMapping(value = "/weshowBindPhone")
    public String showBindPhone(HttpServletRequest request) {
        if (!WebSession.checkLoginStatus(request.getSession())) {
            return "/wesite/view/sign/login";
        }
        return "/wesite/view/home/wxbindphone";
    }

    /**
     * 手机绑定
     */
    @RequestMapping(value = "/webindphone")
    public void webindphone(String phone, String smscode, HttpSession session, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            userService.bindPhone(phone, smscode, session);
            WebUtils.responseWrite(response, json.toString());
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     * 进入忘记密码页面
     */
    @RequestMapping(value = "/resetPassword")
    public String resetPassword() {
        return "/wesite/view/password/reset-password-1";
    }

    /**
     * 注册
     *
     * @param loginname
     * @param mobile
     * @param pwd
     * @param smscode
     * @param regtype
     * @param response
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public void register(String loginname, String mobile, String pwd, String smscode, String regtype, HttpServletResponse response) {
        JsonReturn json = new JsonReturn();
        try {
            if ("phone".equals(regtype)) {
                json.putData(userService.registerByPhone(mobile, pwd, smscode, UserService.UserSourceEnum.WECHAT.ordinal()));
            } else if ("account".equals(regtype)) {
                json.putData(userService.registerByAccount(loginname, mobile, pwd, smscode, UserService.UserSourceEnum.WECHAT.ordinal()));
            }
            WebUtils.responseWrite(response, json.toString("/we/user/login"));
        } catch (Exception e) {
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }
    //进入用户反馈
    @RequestMapping("wxfeedback")
    public  String wxFeedBack(HttpServletRequest request,HttpSession session,Model model ){
        if (!WebSession.checkLoginStatus(request.getSession())) {
            return "/wesite/view/sign/login";
        }
        if(WebSession.checkLoginStatus(session)){
            JdataBean user = userService.getUser(WebSession.getWbUser(session).getUserid());
            model.addAttribute("phone", user.getString("phone"));
        }
        return "/wesite/view/home/userfeedback";
    }
    //保存用户反馈信息
    @RequestMapping("saveFeedBack")
    public void saveFeedBack (String phone, String content, @RequestParam(value = "photoids[]",required = false) String[] photoids, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws ClientException{
        JsonReturn json = new JsonReturn();
        if (!WebSession.checkLoginStatus(request.getSession())) {
            throw new ClientException(CodeEnum.LoginOut);
        }
        try{
            JdataBean bean = new JdataBean();
            if (WebSession.checkLoginStatus(session)) {
                bean.put("userid", WebSession.getWbUser(session).getUserid());
            }
            JdataBean user = userService.getUser(WebSession.getWbUser(session).getUserid());
            String loginname = user.getString("loginname");
            bean.put("loginname",loginname);
            bean.put("type",1);     //添加标识表示微信添加
            bean.put("phone", phone);
            bean.put("content", content);
            if(photoids !=null){
                bean.put("photo",photoids[0]);  //第一张设置为主图片
                bean.put("photoids", photoids);
            }
            userService.writefeedback(bean);
            WebUtils.responseWrite(response, json.toString());
        }catch (Exception e){
            WebUtils.responseWrite(response, json.toErrorString(this.getClass(), e));
        }
    }

    /**
     *
     * 进入我的消息
     */
    @RequestMapping(value = "loadMyMessage")
    public String loadMyMessage(HttpServletRequest request){
        if (!WebSession.checkLoginStatus(request.getSession())) {
            return "/wesite/view/sign/login";
        }
        return "/wesite/view/article/station-news-list";
    }

    /**
     *加载我的消息列表
     * @param pno
     * @param request
     * @param response
     */
    @RequestMapping(value = "myMessage")
    @ResponseBody
    public void myMessage(String pno, HttpServletRequest request,HttpServletResponse response) {
        String userid = WebSession.getWbUser(request.getSession()).getUserid();
        JdataBean user = userService.getUser(userid);
        JsonReturn json = new JsonReturn();
        int pageno = 1;
        if (StringUtils.isNotBlank(pno)) pageno = Integer.parseInt(pno);
        PageResult pr = informationService.queryStationnews(userid, user.getString("grade"), 13, pageno);
        informationService.setStationnewsRead(userid);
        json.putData(pr);
        WebUtils.responseWrite(response, json.toString());
    }
    /**
     * 进入消息详情
     */
    @RequestMapping(value = "MessageDetails")
    public String MessageDetails(String id,HttpServletRequest request,Model model){
        if (!WebSession.checkLoginStatus(request.getSession())) {
            return "/wesite/view/sign/login";
        }
        JdataBean bean = informationService.getStationnews(id);
        if (bean !=null){
            model.addAttribute("list",bean.getDataMap());
        }
        return "/wesite/view/article/station-news";
    }
}


